import { defineStore } from 'pinia'
import { getToken, removeToken } from '@/utils/auth'
import { getInfo, logout } from '@/api/user'
import { listFriendLinkVo } from '@/api/friendLink'
import { getBasicInfo } from '@/api/website'
import { hotArticles } from '@/api/article'

import { listTagVo } from '@/api/tags'
import { TagVo } from '@/api/tags/type'
import { ArticleVo } from '@/api/article/type'
import { WebsiteConfig } from '@/api/website/type'
import { FriendLink } from '@/api/friendLink/type'
import { UserBasic } from '@/api/type'
import { CategoryVo } from '@/api/category/type'
import { listCategoryVos } from '@/api/category'

interface UserState {
  token?: string
  username: string
  summary: string
  gitee: string
  github: string
  qqNumber: string
  weChat: string
  avatar: string
  userBasic: UserBasic
  userId: string
  website: WebsiteConfig
  tags: TagVo[]
  categories: CategoryVo[]
  friendLinkList: FriendLink[]
  hotArticles: ArticleVo[]
}

const useStore = defineStore('user', {
  state: (): UserState => {
    return {
      token: getToken(),
      username: '',
      summary: '',
      gitee: '',
      github: '',
      qqNumber: '',
      weChat: '',
      avatar: '',
      userId: '',
      userBasic: {} as UserBasic,
      website: {} as WebsiteConfig,
      tags: [],
      categories: [],
      friendLinkList: [],
      hotArticles: []
    }
  },
  actions: {
    /** 获取用户登录信息 */
    getInfo() {
      return new Promise<void>((resolve, reject) => {
        getInfo()
          .then(({ data: res }): void => {
            const { data } = res

            if (data == null) {
              reject(new Error('验证失败，请重新登录。'))
            }
            const { username, nickName, avatar, userId, summary, gitee, github, qqNumber, weChat } =
              data
            this.username = nickName || username
            this.avatar = avatar
            this.userId = userId
            this.summary = summary
            this.gitee = gitee
            this.github = github
            this.qqNumber = qqNumber
            this.weChat = weChat
            resolve(data)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /** 退出系统 */
    logOut() {
      return new Promise<void>((resolve, reject) => {
        logout()
          .then(() => {
            this.resetData()
            window.location.reload()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /** 获取系统信息 */
    getSystem() {
      return new Promise<void>((resolve, reject) => {
        getBasicInfo()
          .then(({ data: response }) => {
            this.userBasic = response.data.websiteAdmin
            this.website = response.data.websiteConfig
            document.title = this.website.title
            // 获取指定 meta 标签
            const descriptionMeta = document.querySelector('meta[name="description"]')
            if (descriptionMeta) {
              // 修改 meta 标签的 content 属性
              descriptionMeta.setAttribute('content', this.website.description)
            }
            // 获取其他 meta 标签
            const keywordsMeta = document.querySelector('meta[name="keywords"]')
            if (keywordsMeta) {
              // 修改 meta 标签的 content 属性
              keywordsMeta.setAttribute('content', this.website.keywords)
            }
            // 获取现有的或新建一个 favicon 链接元素
            const faviconLink = document.querySelector('link[rel="icon"]') as HTMLLinkElement
            if (faviconLink) {
              faviconLink.href = `${this.website.logo}?random=${new Date().getTime()}`
            }
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /** 获取标签信息 */
    getTags() {
      return new Promise<void>((resolve, reject) => {
        listTagVo()
          .then(({ data: response }) => {
            this.tags = response.data
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /** 获取分类列表 */
    getCatrgorys() {
      return new Promise<void>((resolve, reject) => {
        listCategoryVos()
          .then(({ data: res }) => {
            this.categories = res.data
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /** 获取友情链接 */
    getFriendLink() {
      return new Promise<void>((resolve, reject) => {
        listFriendLinkVo()
          .then(({ data: response }) => {
            this.friendLinkList = response.data
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /** 获取热门文章 */
    getHot() {
      return new Promise<void>((resolve, reject) => {
        hotArticles()
          .then(({ data: response }) => {
            this.hotArticles = response.data.records
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /** 数据重置 */
    resetData() {
      return new Promise<void>((resolve) => {
        // 重置基础信息
        this.username = ''
        this.summary = ''
        this.gitee = ''
        this.github = ''
        this.qqNumber = ''
        this.weChat = ''
        this.avatar = ''
        this.userId = ''
        this.userBasic = {} as UserBasic
        this.website = {} as WebsiteConfig
        // 清除TOKEN
        removeToken()
        resolve()
      })
    }
  }
})
export default useStore
